import pygame
import time
import random
import json
import rich.console

from plugins.login import welcame

info = {
    "name":"Desktop",
    "version":"2.0",
    "info":"XToolsBox Plus 默认页",
    "by":["This is XiaoDeng"]
}
screenevent = []
screen = None
bg = (0,0,0)

class desktop():
    paused = False
    def __init__(self,api,log,screen):
        self.api = api
        self.log = log
        self.screen = screen
        #self.screen = pygame.surface.Surface(self.screen114514.get_size())
        self.screen.fill((102 ,204 ,255))
    def onStart(self):
        global screenevent
        
        
        # 初始化用户
        self.user = self.api.getglobalvalue("user")
        self.log("set %USER% =",self.user)
        self.user_display_font1 = pygame.font.Font(self.api.getpath("./font.ttf"),25)
        self.uuid_display_font1 = pygame.font.Font(self.api.getpath("./font.ttf"),12)
        
        
        # 初始化时间
        hour = time.localtime()[3]
        self.log("set %HOUR% =",hour)
        if 6 <= hour <= 11:
            self.welcame = f"早上好，{self.user['name']}！"
        elif 13 <= hour <= 17:
            self.welcame = f"下午好，{self.user['name']}！"
        elif 18 <= hour:
            self.welcame = f"晚上好，{self.user['name']}！"
        elif hour <= 5:
            self.welcame = f"晚上好，{self.user['name']}！"
        elif hour == 12:
            self.welcame = f"中午好，{self.user['name']}！"
        else:
            self.welcame = f"Hello, {self.user['name']}!"
            
        
        
        
        # 初始化顶栏
        self.log(self.welcame)
        self.user_display = self.user_display_font1.render(self.welcame,True,(255,255,255),None)
        self.uuid_display = self.uuid_display_font1.render(f'UUID: {self.user["uuid"]}',True,(255,255,255),None)

        self.top = pygame.surface.Surface((600,53))
        self.top.fill((0,255,0))
        self.xh = pygame.surface.Surface((600,400))
        self.xh.fill((255,255,255))
        self.xh.set_alpha(0)
        self.bg = pygame.image.load(self.api.getpath("./desktop/2.jpg"))
        self.bg = pygame.transform.scale(self.bg,(720,450))
        self.screen.blit(self.bg,(self.api.autocenter(self.bg),0))
        
        self.msgfont = pygame.font.Font(self.api.getpath("./font.ttf"), 35)
        self.screen.blit(self.xh,(0,0))
        self.top.set_alpha(50)
        self.screen.blit(self.top,(0,0))
        self.screen.blit(self.user_display,(5,2.5))
        self.screen.blit(self.uuid_display,(5,32.5))

        with open(self.api.getpath("./desktop.cave1.json"),"r",encoding = "utf-8-sig") as f:
            #self.log(f.read())
            cave_list = json.loads(f.read())
        cave1 = random.choice(cave_list)
        
        self.msgfont = pygame.font.Font(self.api.getpath("./font.ttf"), 25)
        self.msg1_1 = self.msgfont.render("欢迎使用XToolsBox+",True,(255,255,255),None)
        self.msg2_1 = pygame.font.Font(self.api.getpath("./font.ttf"), 15).render(cave1,True,(255,255,255),None)
        self.msg3_1 = pygame.font.Font(self.api.getpath("./font.ttf"), 15).render("使 用 空 格 键 进 入 主 页",True,(255,255,255),None)
        # self.screen.blit(self.msg1,(self.api.autocenter(self.msg1),205))
        self.msg1 = self.msg1_1.copy()
        self.msg2 = self.msg2_1.copy()
        self.msg2.set_alpha(0)
        self.msg1.set_alpha(0)
        self.msg3 = self.msg3_1.copy()
        self.msg3.set_alpha(0)

        self.page_list = self.api.getglobalvalue("page_list")
        self.pages = self.api.getglobalvalue("pages")
        y = 97
        self.p = []
        self.x1 = 0
        l = 1
        self.pos = [0,0]
        a = random.randint(0,5)
        self.icons = self.api.main.getvalue("icons")
        x = 20
        self.colors = self.api.getglobalvalue("config")["colors"]
        self.page = "Home_enter"   # Home|List
        screen1 = screen.copy()
        self.wantinto = "<default>"
        self.y4 = 347
        self.wheel = 20
        self.init = False
        # self.api.newThread("事件处理线程-1",self.event1)
        
        while not(self.paused):
            screen.blit(self.inPage(screen1.subsurface((0,53,600,347)).copy()),(0,54))
            
            
            for event in screenevent:
                if event.type == pygame.KEYUP:
                    if self.page[0:4] == "Home":
                        self.xh.set_alpha(35)
                        screen1.blit(self.xh,(0,0))
                        self.page =  "Home to list"
                        self.api.newThread("listinto",self.listinto)
                elif event.type == pygame.MOUSEMOTION:
                    self.pos = event.pos
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    self.log(event)
                    if event.button == 1:
                        self.api.main.setvalue("scr",self.wantinto)
                elif event.type == pygame.MOUSEWHEEL:
                    self.wheel += event.y*5
            screenevent = []

    def inPage(self,screen):
        scr = screen
        #scr.fill((0,0,0))
        #scr.set_colorkey((0,0,0))
        if self.page[0:4] == "Home":
            leftop = pygame.surface.Surface((320,100))
            leftop.fill((0,0,0))
            leftop.set_colorkey((0,0,0))
            pygame.draw.rect(leftop,(0,12,255),(0,0,self.x1,65),0)
            pygame.draw.rect(leftop,(0,53,255),(-5,0,self.x1+5,65),5)
            leftop.set_alpha(95)
            scr.blit(leftop,(0,10))
        if self.page == "Home_enter":
            self.api.newThread("Home::enter::1",self.noliner1)
            self.page = "Home_entering"
            return scr
        elif self.page == "Home_textinto" or self.page == "Home" or self.page == "Home to list":
            scr.blit(self.msg1,(10,18))
            scr.blit(self.msg2,(10,48))
            scr.blit(self.msg3,(self.api.autocenter(self.msg3),320))
            if self.page == "Home to list":
                scr.blit(self.initicon(),(self.wheel,self.y4))
        if self.page == "List":
            scr.blit(self.initicon(),(self.wheel,65))
            for ico in self.icodata:
                #self.log(ico)
                #self.log(self.pos,ico["pos1"][1] <= self.pos[1] <= ico["pos"][1],ico["pos1"][0] <= self.pos[0] <= ico["pos1"][0])
                try:
                    #self.log(ico,ico["pos1"][0] <= self.pos[0] - self.wheel <= ico["pos2"][0],ico["pos1"][1] <= self.pos[1]-50 <= ico["pos2"][1])
                    if ico["pos1"][0] <= self.pos[0] - self.wheel <= ico["pos2"][0]:
                        if ico["pos1"][1] <= self.pos[1]-50 <= ico["pos2"][1]:
                            pygame.draw.rect(scr,(255,255,255),(ico["pos1"][0]+self.wheel,ico["pos1"][1],ico["pos2"][0] - ico["pos1"][0],ico["pos2"][1] - ico["pos1"][1]),3)
                            self.wantinto = ico["id"]
                            #self.log(self.wantinto)
                        elif self.wantinto == ico["id"]:
                            self.wantinto = "<default>"
                    elif self.wantinto == ico["id"]:
                        self.wantinto = "<default>"
                except:
                    rich.console.Console().print_exception()
        
        return scr
            
    def noliner1(self):
        x1 = max(self.msg1_1.get_size()[0],self.msg2_1.get_size()[0]) + 50
        speed = 0.19
        exit = 1
        started = 0
        
        while exit == 1:
            #print(1)
            self.x1 += (x1 - self.x1) / 2 * speed
            pygame.time.delay(30)
            if x1 - self.x1 <= 1:
                exit = 0
            if x1 - self.x1 <= 30 and started == 0:
                started = 1
                self.page = "Home_textinto"
                self.api.newThread("Home::Textinto",self.into1)
        x3 = 320
        self.log("exit")
        self.init = True
    def noliner2(self):
        x1 = 0
        speed = 0.19
        exit = 1
        started = 0
        
        while exit == 1:
            #print(1)
            self.x1 -= (self.x1 - x1) / 2 * speed
            pygame.time.delay(10)
            if self.x1 - x1 <= 1:
                exit = 0
                #self.page = "Home_textinto"
                #self.api.newThread("Home::Textinto",self.into1)
        x3 = 90
    def listinto(self):
        if self.init:
            self.listinto1()
    def listinto1(self):
        x1 = 65
        speed = 0.19
        exit = 1
        
        self.into2()
        self.noliner2()
        started = 0
        self.log(self.y4 - x1)
        while exit == 1:
            self.log(self.y4 - x1)
            #print(1)
            self.y4 -= (self.y4 - x1) / 2 * speed
            pygame.time.delay(30)
            if self.y4 - x1 <= 1:
                exit = 0
            if self.y4 - x1  <= 30 and started == 0:
                started = 1
        self.y4 = 65
        self.page = "List"
        #self.log(self.y4 - x1)
    def into1(self):
        for i in range(40):
            self.msg1.set_alpha(i*5)
            self.msg2.set_alpha(i*5)
            #self.log(self.msg1.get_alpha())
            pygame.time.delay(20)
        self.msg1 = self.msg1_1.copy()
        #self.msg2 = self.msg2_1.copy()
        time.sleep(1)
        for i in range(40):
            self.msg3.set_alpha(i*5)
            #self.log(self.msg1.get_alpha())
            pygame.time.delay(10)
    def into2(self):
        for i in range(20):
            self.msg1.set_alpha(100 - i*5)
            self.msg2.set_alpha(100 - i*5)
            self.msg3.set_alpha(100 - i*5)
            #self.log(self.msg1.get_alpha())
            pygame.time.delay(5)
        #self.msg1 = self.msg1_1.copy()
        #self.msg2 = self.msg2_1.copy()
    def pause(self):
        pass
    def unpause(self):
        pass

    def initicon(self):
        icon = self.api.main.getvalue("icons")
        #self.log(icon)
        lis = pygame.surface.Surface((600,205))
        lis.fill((0,0,0))
        lis.set_colorkey((0,0,0))
        x = 0
        x1 = 0
        y = 0
        self.icodata = []
        for ico in icon:
            a = self.initico1(ico)
            #self.log(y + a.get_size()[1] + 5 )
            if y + a.get_size()[1] > 205:
                y = 0
                x += x1 +5
            else:
                x1 = max(x1,a.get_size()[0])
                
            lis.blit(a,(x,y))
            self.icodata += [
                {
                    "id":ico["name"],
                    "pos1":[
                        x,
                        y + 65
                    ],
                    "pos2":[
                        x+a.get_size()[0],
                        y+65+a.get_size()[1]
                    ]
                }
            ] 
            y += a.get_size()[1]+5
        #self.log(lis,random.randint(0,114514))
        return lis

    def initico1(self,ico):
        if ico["surface"]:
            # 大磁贴
            sur = ico["surface"]
            surface = pygame.surface.Surface((205,205))
            surface.fill(ico["color"][1])
            sur.set_colorkey((0,0,0))
            surface.blit(sur,(5,5))
            
            surface.blit(pygame.font.Font(self.api.getpath("./font.ttf"),15).render(ico["name"],True,(255,255,255),None),(5,180))
            pygame.draw.rect(surface,ico["color"][0],(0,0,205,205),3)
            return surface
        else:
            # 中等磁贴
            icon = self.api.main.getvalue("pages")[ico["name"]]
            sur = pygame.transform.scale(icon["icon"],(80,80))
            surface = pygame.surface.Surface((100,100))
            surface.fill(ico["color"][1])
            surface.blit(sur,(10,10))
            surface.blit(pygame.font.Font(self.api.getpath("./font.ttf"),15).render(ico["name"],True,(255,255,255),None),(5,80))
            pygame.draw.rect(surface,ico["color"][0],(0,0,100,100),3)
            return surface
            



class plugin():
    def __init__(self,api,log):
        global screen
        self.log = log
        self.api = api
        screen = self.api.addpage("<default>",desktop,f"{self.api.getpath('./tb')}/launch.png",settings = {"desktop.display":0,"desktop.title":True})
    def onEvent(self,event):
        global screenevent
        if self.api.main.getvalue("scr") == "<default>":
            screenevent += [event]
